/**
 * [getObjById 根据ID获取树上对应id的对象]
 * @param  {[Array]} data [树的数据]
 * @param  {[String]} id   [需要获取的id]
 * @return {[Object]}      [对象]
 */
export const getObjById = (data, id) => {
    if(!data || !data.length || !id) return {};
    const newData = [];
    for(let i = 0; i < data.length; i++) {
        /*eslint-disable  eqeqeq*/
        if(data[i].id == id)
            return data[i];
        if(data[i].items)
            newData.push(...data[i].items);
    }
    return getObjById(newData, id);
};

/**
 * [getPathById 根据ID获取树上对应id的对象]
 * @param  {[Array]} data [树的数据]
 * @param  {[String]} id   [需要获取的id]
 * @return {[Array]}      [path]
 */
export const getPathById = (data, id) => {
    for(let i = 0; i < data.length; i++) {
        const organization = data[i];
        /*eslint-disable  eqeqeq*/
        if(organization.id == id)
            return [i];
        if(organization.items && organization.items.length > 0) {
            const path = getPathById(organization.items, id);
            if(path)
                return [i, 'items'].concat(path);
        }
    }
};

/**
 *  转换ant table的sorter对象转换成分页的查询的排序字段
 * @param {object} sorter
 */
export const conventSorter = sorter => {
    const option = {};
    if(sorter)
        if(sorter.order && sorter.field) {
            // 点击排序
            option.sortField = sorter.field;
            if(sorter.order === 'descend') option.isDesc = true;
            else option.isDesc = false;
        } else {
            // 取消排序
            option.sortField = undefined;
            option.isDesc = undefined;
        }
    return option;
};
export const hasPermissions = (data, name) => Array.isArray(data) && data.length > 0 && data.some(item => item === name);
/* eslint-disable prefer-const, no-bitwise, no-mixed-operators */
import difference from 'lodash/difference';
export const computeSelectedRows = (preKeys, preRows, currentKeys, currentRows, keyIndex = 'id') => {
    if(currentKeys.length === 0)
        return [];
    // 勾选
    if(currentKeys.length > preKeys.length) {
        const newKeys = difference(currentKeys, preKeys);
        const newRows = [];
        newKeys.forEach(key => {
            const row = currentRows.find(r => r[keyIndex] === key);
            if(row)
                newRows.push(row);
        });
        return [...preRows, ...newRows];
    } else if(currentKeys.length < preKeys.length) { // 取消勾选
        const deleteKeys = difference(preKeys, currentKeys);
        const newRows = preRows.filter(d => !deleteKeys.includes(d[keyIndex]));
        return newRows;
    }
    return preRows;
};

export const uuid = () =>
    'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
        let r = (Math.random() * 16) | 0,
            v = c === 'x' ? r : (r & 0x3) | 0x8;
        return v.toString(16);
    });
import {formatMessage} from './intl';
import {warrantyPolicyType} from '../Enum';
import {isEqual, groupBy, pickBy} from 'lodash';
export const validateAdd = (data, id) => {
    const {code, name, brandId, dealerId, startDate, details = []} = data;
    const msgs = [];
    const detailMsg = [];
    if(!brandId && !id)
        msgs.push(
            formatMessage({
                id: 'utils.brandId',
                defaultMessage: '品牌'
            })
        );
    if(!dealerId && !id)
        msgs.push(
            formatMessage({
                id: 'utils.dealerId',
                defaultMessage: '总代'
            })
        );
    if(!code && !id)
        msgs.push(
            formatMessage({
                id: 'utils.code',
                defaultMessage: '编号'
            })
        );
    if(!name)
        msgs.push(
            formatMessage({
                id: 'utils.name',
                defaultMessage: '名称'
            })
        );
    if(!startDate)
        msgs.push(
            formatMessage({
                id: 'utils.startDate',
                defaultMessage: '执行日期'
            })
        );
    if(!details.length)
        msgs.push(
            formatMessage({
                id: 'utils.details',
                defaultMessage: '条款信息'
            })
        );
    if(msgs.length)
        return {
            message: `${msgs.join(
                formatMessage({
                    id: 'utils.comma',
                    defaultMessage: '、'
                })
            )}${formatMessage({
                id: 'utils.notEmpty',
                defaultMessage: '不能为空'
            })}`,
            detailId: '',
            isOk: false
        };
    const detailsArr = [];
    for(let i = 0; i < details.length; i++) {
        const {id, type, warrantyDuration, warrantyMileage, vehicleCategoryItems = [], vehicleItems = []} = details[i];
        if(!type)
            return {
                message: formatMessage({
                    id: 'utils.type.notEmpty',
                    defaultMessage: '索赔类型不能为空'
                }),
                detailId: id,
                isOk: false
            };
        if(!warrantyMileage)
            detailMsg.push(
                formatMessage({
                    id: 'utils.warrantyMileage',
                    defaultMessage: '索赔里程'
                })
            );
        if(!warrantyDuration)
            detailMsg.push(
                formatMessage({
                    id: 'utils.warrantyDuration',
                    defaultMessage: '索赔时间（月）'
                })
            );
        if(detailMsg.length)
            return {
                message: `${detailMsg.join(
                    formatMessage({
                        id: 'utils.comma',
                        defaultMessage: '、'
                    })
                )}${formatMessage({
                    id: 'utils.detailMsg.validate',
                    defaultMessage: '需要大于 0'
                })}`,
                detailId: id,
                isOk: false
            };
        if(type === warrantyPolicyType.标准 && !vehicleCategoryItems.length)
            msgs.push(
                formatMessage({
                    id: 'utils.vehicleCategoryItems',
                    defaultMessage: '车型清单'
                })
            );
            
        if(type === warrantyPolicyType.特殊 && !vehicleItems.length)
            msgs.push(
                formatMessage({
                    id: 'utils.vehicleItems',
                    defaultMessage: '车辆清单'
                })
            );
        if(msgs.length)
            return {
                message: `${msgs.join(
                    formatMessage({
                        id: 'utils.comma',
                        defaultMessage: '、'
                    })
                )}${formatMessage({
                    id: 'utils.notEmpty',
                    defaultMessage: '不能为空'
                })}`,
                detailId: id,
                isOk: false
            };
        const detailOnly = detailsArr.some(item => isEqual(item, {
            type,
            warrantyDuration,
            warrantyMileage
        }));
        if(detailOnly)
            return {
                message: `${formatMessage({
                    id: 'utils.detailOnly',
                    defaultMessage: '索赔类型 + 索赔里程 + 索赔时间（月）不能重复'
                })}`,
                detailId: id,
                isOk: false
            };
        detailsArr.push({
            type,
            warrantyDuration,
            warrantyMileage
        });
        if(type === warrantyPolicyType.标准) {
            const vehiclePropertyObj = {};
            for(let k = 0; k < vehicleCategoryItems.length; k++) {
                const categoryMsg = [];
                const {id: pid, productCategoryId, vehicleProperty} = vehicleCategoryItems[k];
                if(categoryMsg.length)
                    return {
                        message: `${formatMessage({
                            id: 'utils.categoryMsg',
                            defaultMessage: '车型清单中'
                        })} ${categoryMsg.join(
                            formatMessage({
                                id: 'utils.comma',
                                defaultMessage: '、'
                            })
                        )} ${formatMessage({
                            id: 'utils.notEmpty',
                            defaultMessage: '不能为空'
                        })}`,
                        detailId: id,
                        itemId: pid,
                        isOk: false
                    };
                if(!vehiclePropertyObj[productCategoryId])
                    vehiclePropertyObj[productCategoryId] = [vehicleProperty];
                else if(vehiclePropertyObj[productCategoryId].includes(vehicleProperty))
                    return {
                        message: `${formatMessage({
                            id: 'utils.productCategoryId.notEmpty',
                            defaultMessage: '同一车型的车辆属性不能相同'
                        })}`,
                        detailId: id,
                        itemId: pid,
                        isOk: false
                    };
                else
                    vehiclePropertyObj[productCategoryId].push(vehicleProperty);
            }
        }
            
        if(type === warrantyPolicyType.特殊)
            for(let k = 0; k < vehicleItems.length; k++) {
                const {vehicleId, parts = []} = vehicleItems[k];
                if(!parts.length)
                    return {
                        message: `${formatMessage({
                            id: 'utils.vehicleMsg',
                            defaultMessage: '车辆清单中备件清单不能为空'
                        })}`,
                        detailId: id,
                        itemId: vehicleId,
                        isOk: false
                    };
                if(Object.keys(pickBy(groupBy(vehicleItems[k], 'vehicleId'), values => values.length > 1)).length > 1)
                    return {
                        message: `${formatMessage({
                            id: 'validate.vehicleProperty.notEmpty1',
                            defaultMessage: '车辆不能重复'
                        })}`,
                        detailId: id,
                        itemId: vehicleId,
                        isOk: false
                    };
            }
    }
    return false;
};
